<template>
  <div class="filter-section">
    <span class="filter-label">到期日期</span>
    <div class="tag-container">
      <span
        v-for="tag in dueDateTags"
        :key="tag.value"
        class="text-tag"
        :class="{ active: tag.type === 'primary' }"
        @click="handleDueDateTagClick(tag)"
      >
        <span class="text-tag-label">{{ tag.label }}</span>
        <span class="text-tag-close" @click.stop="handleDueDateClose(tag)">×</span>
      </span>

      <div v-if="dueDateInputVisible" class="range-input-container">
        <el-date-picker
          v-model="dueDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="large"
          :disabled-date="disablePastDates"
          value-format="YYYY-MM-DD"
          unlink-panels
        />
        <el-button type="primary" size="small" @click="handleDueDateInputConfirm" class="confirm-btn"> 确认 </el-button>
        <el-button size="small" @click="dueDateInputVisible = false" class="cancel-btn"> 取消 </el-button>
      </div>
      <el-button v-else class="button-new-tag" size="large" @click="showDueDateInput"> + 新增日期范围 </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue"
import { ElMessage } from "element-plus"
import {
  getRateDateRangesAllListApi,
  createRateDateRangeApi,
  deleteRateDateRangeApi
} from "../../../../../api/calculator/index"
import type { TagItem, RateItem } from "./types"

// Props
interface Props {
  modelValue?: TagItem[]
  selectedRangeId?: number
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  selectedRangeId: undefined
})

// Emits
const emit = defineEmits<{
  "update:modelValue": [value: TagItem[]]
  change: [selectedDates: TagItem[]]
  dateSelect: [tag: TagItem]
}>()

// 到期日期标签数据
const dueDateTags = ref<TagItem[]>([])

// 输入框状态
const dueDateInputVisible = ref<boolean>(false)
const dueDateRange = ref<[string, string] | undefined>(undefined)

// 监听选中的金额区间变化
watch(
  () => props.selectedRangeId,
  async (newRangeId) => {
    if (newRangeId) {
      await loadDueDateTags(newRangeId)
    } else {
      dueDateTags.value = []
      emit("update:modelValue", dueDateTags.value)
    }
  },
  { immediate: true }
)

/**
 * 处理到期日期标签点击（单选）
 * 点击后清空其他选中，仅保留当前，并联动利率
 */
const handleDueDateTagClick = async (tag: TagItem) => {
  // 单选：清空所有，再选中当前
  dueDateTags.value.forEach((t) => (t.type = ""))
  tag.type = "primary"

  emit("update:modelValue", dueDateTags.value)
  emit("dateSelect", tag)

  const selectedDates = dueDateTags.value.filter((t) => t.type === "primary")
  emit("change", selectedDates)
}

/**
 * 删除到期日期标签：调用后端接口删除，并刷新列表与利率
 */
const handleDueDateClose = async (tag: TagItem) => {
  // 解析 date_range_id
  const dateRangeId = Number(tag.value)
  if (!Number.isFinite(dateRangeId)) {
    ElMessage.error("无效的到期日期标识")
    return
  }
  try {
    const res = await deleteRateDateRangeApi({ date_range_id: dateRangeId })
    if (res.code === 200) {
      ElMessage.success("删除到期日期范围成功")
      // 刷新到期日期列表（根据当前金额或类型上下文）
      if (props.selectedRangeId) {
        await loadDueDateTags(props.selectedRangeId)
      }
    } else {
      ElMessage.error(res.message || "删除到期日期范围失败")
    }
  } catch (e) {
    console.error("删除到期日期范围失败:", e)
    ElMessage.error("删除到期日期范围失败")
  }
}

// 显示到期日期输入框
const showDueDateInput = () => {
  dueDateInputVisible.value = true
  dueDateRange.value = undefined
}

// 确认到期日期输入
const handleDueDateInputConfirm = async () => {
  // 读取日期范围
  let startValue = ""
  let endValue = ""
  if (dueDateRange.value && Array.isArray(dueDateRange.value)) {
    const [start, end] = dueDateRange.value
    startValue = (start || "").toString().trim()
    endValue = (end || "").toString().trim()
  }
  if (!startValue || !endValue) {
    ElMessage.error("请选择开始和结束日期")
    return
  }

  // 获取当前选中的金额区间 range_id
  const rangeId = props.selectedRangeId
  if (!rangeId || !Number.isFinite(rangeId)) {
    ElMessage.error("请先选择金额区间")
    return
  }

  try {
    const res = await createRateDateRangeApi({
      range_id: rangeId,
      start_date: startValue,
      end_date: endValue
    })
    if (res.code === 200) {
      ElMessage.success("新增到期日期范围成功")
      // 重新加载到期日期列表
      await loadDueDateTags(rangeId)
      // 关闭面板并清空
      dueDateInputVisible.value = false
      dueDateRange.value = undefined
    } else {
      ElMessage.error(res.message || "新增到期日期范围失败")
    }
  } catch (e) {
    console.error("新增到期日期范围失败:", e)
    ElMessage.error("新增到期日期范围失败")
  }
}

// 禁用今天及之前的日期（只能选择当天之后）
const disablePastDates = (time: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return time.getTime() <= today.getTime()
}

const loadDueDateTags = async (rangeId?: number) => {
  try {
    const params: any = {}
    if (rangeId) params.range_id = rangeId
    const res = await getRateDateRangesAllListApi(params)
    if (res.code === 200 && res.data) {
      const list = res.data as any[] as RateItem[]
      dueDateTags.value = list.map((item, index) => {
        const label = `${item.start_date} - ${item.end_date}`
        const value = String(item.date_range_id ?? `${item.start_date}-${item.end_date}`)
        return {
          label,
          value,
          type: index === 0 ? "primary" : ""
        }
      })

      emit("update:modelValue", dueDateTags.value)

      // 触发选中事件
      const selectedDates = dueDateTags.value.filter((t) => t.type === "primary")
      if (selectedDates.length > 0) {
        emit("change", selectedDates)
        emit("dateSelect", selectedDates[0])
      }
    } else {
      dueDateTags.value = []
      emit("update:modelValue", dueDateTags.value)
    }
  } catch (e) {
    console.error("加载到期日期失败:", e)
    ElMessage.error("加载到期日期失败")
    dueDateTags.value = []
    emit("update:modelValue", dueDateTags.value)
  }
}

// 暴露方法给父组件
defineExpose({
  loadDueDateTags,
  getSelectedDates: () => dueDateTags.value.filter((t) => t.type === "primary")
})
</script>

<style scoped>
.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.filter-label {
  font-weight: 500;
  color: #333;
  margin-right: 15px;
  min-width: 70px;
  font-size: 14px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.range-input-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.confirm-btn,
.cancel-btn {
  margin-left: 5px;
}

.button-new-tag {
  border-style: dashed;
  color: #999;
}

.button-new-tag:hover {
  color: #409eff;
  border-color: #409eff;
}

/* 文本标签样式（替代 el-tag） */
.text-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
  border: 1px solid transparent;
  user-select: none;
}
.text-tag:hover {
  color: #409eff;
}
.text-tag.active {
  color: #409eff;
  font-weight: 500;
  border-color: rgba(64, 158, 255, 0.2);
  background-color: rgba(64, 158, 255, 0.05);
}
.text-tag-close {
  margin-left: 4px;
  color: #bbb;
  font-weight: bold;
  cursor: pointer;
}
.text-tag-close:hover {
  color: #f56c6c;
}
.text-tag-label {
  line-height: 1;
}
</style>
